<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary" round @click="showAddCategories">添加分类</el-button>
      </div>
      <tree-table
        :show-row-hover="false"
        :show-index="true"
        index-text="#"
        border
        :expand-type="false"
        :selection-type="false"
        :data="cateList"
        :columns="columns"
      >
        <template slot="isOk" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted==false" style="color:lightgreen"></i>
          <i class="el-icon-error" v-else style="color:red"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag size="mini" type="success" v-else-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            round
            class="r_m_btns"
            @click="editCategories(scope.row.cat_id)"
          >编辑</el-button>

          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            round
            class="r_m_btns"
            @click="deleteCategories(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </tree-table>
      <!-- 分页 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[2, 5, 10, 15]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加分类对话框 -->
      <el-dialog
        @close="resetAddCategoriesForm"
        title="添加分类"
        :visible.sync="addCategoriesDialogVisible"
        width="30%"
        center
      >
        <el-form
          :model="addCategoriesForm"
          :rules="addCategoriesRules"
          ref="addCategoriesRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="分类名称：" prop="cat_name">
            <el-input v-model="addCategoriesForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类：">
            <el-cascader
              v-model="selectedKeys"
              :options="parentCategoriesList"
              :props="cascaderProps"
              @change="cascaderChange"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addCategoriesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCategories">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑分类对话框 -->
      <el-dialog
        @close="resetEditCategoriesForm()"
        title="编辑分类"
        :visible.sync="editCategoriesDialogVisible"
        width="30%"
        center
      >
        <el-form
          :model="editCategoriesForm"
          :rules="addCategoriesRules"
          ref="editCategoriesRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="分类名称：" prop="cat_name">
            <el-input v-model="editCategoriesForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editCategoriesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="subEditCategories()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryData: {
        type: 3,
        pagenum: 1,
        pagesize: 10
      },
      cateList: [],
      total: 0,
      //表格各列配置
      columns: [
        {
          label: "分类名称",
          prop: "cat_name"
        },
        {
          //表格列名称
          label: "是否有效",
          type: "template",
          // 模板名称
          template: "isOk"
        },
        {
          label: "排序",
          type: "template",
          template: "order"
        },
        {
          label: "操作",
          type: "template",
          template: "opt"
        }
      ],
      // 控制添加分类对话框显示隐藏
      addCategoriesDialogVisible: false,
      //添加分类的表单数据
      addCategoriesForm: {
        cat_name: "",
        cat_id: 0,
        // 分类父 ID
        cat_pid: 0,
        // 分类层级
        cat_level: 0
      },
      // 添加分类规则
      addCategoriesRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      // 父级分类
      parentCategoriesList: [],
      // 级联选择器配置属性
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true
      },
      // 级联选择器选择值的数组
      selectedKeys: [],
      // 控制编辑分类对话框
      editCategoriesDialogVisible: false,
      // 编辑分类数据列表
      editCategoriesForm: {}
    };
  },

  created() {
    this.getCategoriesList();
  },

  methods: {
    // 获取产品参数数据
    async getCategoriesList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryData
      });
      if (res.meta.status !== 200) return this.$message.error("加载失败");
      this.cateList = res.data.result;
      this.total = res.data.total;
      console.log(this.cateList);
      console.log(this.total);
    },
    //改变每页显示的条数
    handleSizeChange(val) {
      this.queryData.pagesize = val;
      this.getCategoriesList();
    },
    // 当前页
    handleCurrentChange(val) {
      this.queryData.pagenum = val;
      this.getCategoriesList();
    },
    showAddCategories() {
      this.getAddCategories();
      this.addCategoriesDialogVisible = true;
    },
    // 获取父级分类
    async getAddCategories() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 }
      });
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("父级分类列表加载失败");
      this.parentCategoriesList = res.data;
    },
    // 级联选择器选择值变化时触发
    cascaderChange() {
      console.log(this.selectedKeys);
      if (this.selectedKeys.length > 0) {
        // 父分类id为selectedKeys的最后一项
        this.addCategoriesForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ];
        // 分类等级为selectedKeys的长度
        this.addCategoriesForm.cat_level = this.selectedKeys.length;
      } else {
        this.addCategoriesForm.cat_pid = 0;
        this.addCategoriesForm.cat_level = 0;
      }
      console.log(this.addCategoriesForm.cat_pid);
      console.log(this.addCategoriesForm.cat_level);
    },
    resetAddCategoriesForm() {
      // 清除表单数据
      this.$refs.addCategoriesRef.resetFields();
      // 清除addCategoriesForm数据
      this.addCategoriesForm.cat_pid = 0;
      this.addCategoriesForm.cat_level = 0;
      // 清除级联选择器保存的数据
      this.selectedKeys = [];
    },
    //点击确定提交新增分类
    addCategories() {
      this.$refs.addCategoriesRef.validate(async flag => {
        if (!flag) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCategoriesForm
        );
        if (res.meta.status !== 201) return this.$message.error("添加分类失败");
        this.$message.success("添加分类成功");
        this.addCategoriesDialogVisible = false;
        this.getCategoriesList();
      });
    },
    // 编辑分类
    async editCategories(id) {
      const { data: res } = await this.$http.get(`categories/${id}`);
      if (res.meta.status !== 200) return this.$message.error("分类加载失败");
      this.editCategoriesForm = res.data;
      this.editCategoriesDialogVisible = true;
    },
    async subEditCategories() {
      this.$refs.editCategoriesRef.validate(async flag => {
        if (!flag) return;
        const {
          data: res
        } = await this.$http.put(
          `categories/${this.editCategoriesForm.cat_id}`,
          { cat_name: this.editCategoriesForm.cat_name }
        );
        if (res.meta.status !== 200) return this.$message.error("分类加载失败");
        this.$message.success("分类名称编辑成功");
        this.$refs.editCategoriesRef.resetFields();
        this.editCategoriesDialogVisible = false;
      });
      this.getCategoriesList();
    },
    resetEditCategoriesForm() {
      // 清除表单数据
      this.$refs.editCategoriesRef.resetFields();
    },
    deleteCategories(id) {
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`categories/${id}`);
          if (res.meta.status !== 200) return this.$message.error("删除失败");
          this.$message.success("删除成功");
          this.getCategoriesList();
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    }
  }
};
</script>

<style scoped lang='less'>
.el-breadcrumb {
  margin-bottom: 20px;
  padding: 15px;
}
.el-cascader {
  width: 100%;
}
</style>
